package com.aluvfy.jdbc;

import java.sql.*;
import java.util.ResourceBundle;

public class JDBCTest06 {
    public static void main(String[] args) {
        //读取属性配置文件，读取数据库连接
        ResourceBundle bundle = ResourceBundle.getBundle("com.aluvfy.jdbc.jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stm = null;
        ResultSet rs = null;

        //ctrl alt t 异常处理
        try {
            //1. 注册驱动
            Class.forName(driver);
            //2. 获取连接
            conn = DriverManager.getConnection(url, user, password);
            //3. 获取数据库操作对象
            stm = conn.createStatement();
            //4. 执行sql语句
            String sql = "INSERT INTO t_product(name, price, create_time) VALUES('小米酥', 1.0, '2024-02-04')";
            //注意：第二个参数是标志位，用来表示是否将新插入数据的主键值返回
            int count = stm.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            System.out.println("传入了"  + count + "条数据");
            //获取新增的主键值
            //返回的rs结果集中包含了新增的主键值
            rs = stm.getGeneratedKeys();
            //通过结果集取主键值
            while (rs.next()){
                Long id = rs.getLong(1);
                System.out.println("新增的主键值是：" + id);
            }


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //6. 关闭资源
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (stm != null) stm.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
